package com.kim.whereeat.service;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.kim.whereeat.model.UserInfo;
import com.kim.whereeat.utils.SQLiteHelper;

/**
 * Created by 伟阳 on 2015/10/24.
 */
public class UserInfoService {
    private SQLiteHelper helper;

    public UserInfoService(Context context) {
        helper = new SQLiteHelper(context);
    }

    /**
     * 判断是否存在此用户名
     *
     * @param username 用户名
     * @return true存在/false不存在
     */
    public boolean exists(String username) {
        boolean flag = false;
        SQLiteDatabase dbReader = helper.getReadableDatabase();
        Cursor cursor = dbReader.query("userinfo", null, "username=?", new String[]{username}, null, null, null);
        flag = cursor.getColumnCount() > 0;
        cursor.close();
        return flag;
    }

    public UserInfo getUserInfoById(int userId) {
        UserInfo userInfo = null;
        SQLiteDatabase dbReader = helper.getReadableDatabase();
        Cursor cursor = dbReader.query("userinfo", null, "id=?", new String[]{userId + ""}, null, null, null);
        if (cursor.moveToNext()) {
            userInfo = new UserInfo();
            userInfo.setId(cursor.getInt(0));
            userInfo.setUsername(cursor.getString(1));
            userInfo.setPassword(cursor.getString(2));
        }
        return userInfo;
    }

    /**
     * 判断登陆
     *
     * @param username 用户名
     * @param password 密码
     * @return -1登陆失败/userId
     */
    public int login(String username, String password) {
        int userId = -1;
        SQLiteDatabase dbReader = helper.getReadableDatabase();
        Cursor cursor = dbReader.query("userinfo", new String[]{"id"}, "username=? and password=?", new String[]{username, password}, null, null, null);
        if (cursor.moveToNext()) {
            userId = cursor.getInt(0);
        }
        cursor.close();
        return userId;
    }

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return true注册成功/false注册失败
     */
    public boolean register(String username, String password) {
        boolean flag = false;
        SQLiteDatabase dbWriter = helper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", username);
        cv.put("password", password);
        long t = dbWriter.insert("userinfo", null, cv);
        flag = t > 0;
        return flag;
    }

    /**
     * 关闭数据库
     */
    public void close() {
        if (helper != null)
            helper.close();
    }
}
